package com.nuc.thread.semaphore;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Semaphore;

/**
 * @author 诗酒趁年华
 * @version 1.0.0
 * @Description
 * @createTime 2021年08月14日 20:40:00
 */
@Slf4j(topic = "TestSemaPhore")
public class TestSemaPhore {
    public static void main(String[] args) {
        Semaphore semaphore  = new Semaphore(3);//信号量：同一时刻最多只能运行三个线程

        for (int i = 0; i <10; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                try {
                    log.debug("running...");
                    Thread.sleep(1000);
                    log.debug("ending...");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();
                }

            },"t"+i).start();
        }
    }
}
